package com.fs.web.base.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.baseMapper.*;
import com.fs.web.base.utils.CollectionTools;
import com.fs.web.base.utils.EncodeUtil;
import com.fs.web.base.vo.LoginUser;
import com.fs.common.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author ACE
 * @desc 登录业务类
 * @creationTime 2019-04-03 21:30
 * @projectName weixinframe
 * @packageName com.fs.base.service
 */
@Slf4j
@Service
public class LoginSerevice {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private MenuMotionMapper menuMotionMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleRightMapper roleRightMapper;

    public LoginUser login(User user){
        LoginUser loginVo = null;
        String account = user.getAccount();
        User u = null;
        Company company = null;
        try {
            String pwd = EncodeUtil.getSignAndMD5(user.getPwd());
            u = userMapper.findByAccountAndPwd(account,pwd);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        if(u!=null){
            if("1".equals(u.getUserStatus())){
                loginVo = LoginUser.builder().user(user).loginStatus(false)
                        .loginResult("该账号已被禁用，请联系系统管理员!").loginTime(new Date()).build();
                return loginVo;
            }
            company = companyMapper.selectById(u.getComId());
            if(company == null){
                loginVo = LoginUser.builder().user(user).loginStatus(false)
                        .loginResult("该账号未绑定部门，请联系系统管理员").loginTime(new Date()).build();
                return loginVo;
            }else if("1".equals(company.getCompanyStatus())){
                loginVo = LoginUser.builder().user(user).loginStatus(false)
                        .loginResult("该部门已被禁用，请联系系统管理员").loginTime(new Date()).build();
                return loginVo;
            }
            /*if(isVerificationCode){
                if("0".equals(company.getMessageStatus())){//短信验证码
                    loginVo = LoginUser.builder().user(u).loginStatus(false)
                            .loginResult("验证码错误").loginTime(new Date()).build();
                    loginVo.setVerificationStatus(true);
                    return loginVo;
                }
            }*/
            Boolean sysAdm = u.isSysAdm();
            loginVo = LoginUser.builder().user(u).loginStatus(true)
                    .loginResult("登录成功!").loginTime(new Date()).build();
            List<Role> roles = new ArrayList<Role>();
            List<Menu> menus = new ArrayList<Menu>();
            List<MenuMotion> motions = new ArrayList<MenuMotion>();
            //排序
            QueryWrapper<Menu> wrapper = new QueryWrapper<>();
            wrapper.orderByAsc("menu_order");
            if(sysAdm){
                menus = menuMapper.selectList(wrapper);
                Set<Object> menuIds = CollectionTools.convertListFeild2Set(menus, "id");
                List<MenuMotion> _motions = menuMotionMapper.findByMenuIdInOrderByMotionOrderAsc(menuIds);
                motions.addAll(_motions);
            }else{
                List<Role> _roles = userRoleMapper.findRoleByUserId(u.getId());
                if(_roles == null || _roles.size()==0){
                    loginVo = LoginUser.builder().user(user).loginStatus(false)
                            .loginResult("该用户尚未配置角色，请联系管理员或客服").loginTime(new Date()).build();
                    return loginVo;
                }
                roles.addAll(_roles);

                /*
                 * 所有菜单动作权限
                 */
                List<UserRole> userRole = userRoleMapper.findByUserId(u.getId());
                List<String> id = new ArrayList<>();
                for (UserRole ur : userRole) {
                    id.add(ur.getRoleId());
                }
                List<RoleRight> roleRight = roleRightMapper.findUserRolesMenuMotion(id);
                id.clear();
                for (RoleRight rr : roleRight) {
                    id.add(rr.getMenuMotionId());
                }
                List<MenuMotion> _motions = menuMotionMapper.findById(id);
                motions.addAll(_motions);

                /*
                 * 所有菜单权限
                 */
                Set<Object> _menuId = CollectionTools.convertListFeild2Set(_motions, "menuId");
                List<Menu> _menus = menuMapper.findByIdInOrderByMenuOrderAsc(_menuId);
                menus.addAll(_menus);

                List<Menu> parents = findParentMenus(menus);
                menus.addAll(parents);
            }
            /*
             * 角色权限
             */
            loginVo.setRoles(roles);
            /*
             * 菜单权限
             */
            loginVo.setMenus(menus);

            /*
             * 动作权限
             */
            Map<String, List<MenuMotion>> menuMotionMap = new HashMap<String, List<MenuMotion>>();
            String menuKey = null;
            for(MenuMotion mm: motions){
                List<MenuMotion> tempList = null;
                menuKey = mm.getMenuId();
                if(menuMotionMap.containsKey(menuKey)){
                    tempList = menuMotionMap.get(menuKey);
                }else{
                    tempList = new ArrayList<MenuMotion>();
                }
                tempList.add(mm);
                menuMotionMap.put(menuKey, tempList);
            }
            loginVo.setMotions(menuMotionMap);
        }else{
            loginVo = LoginUser.builder().user(user).loginStatus(false)
                    .loginResult("用户名或密码错误!").loginTime(new Date()).build();
        }
        return loginVo;
    }

    /**
     * 递归获取所有父菜单
     * @param list
     * @return
     */
    private List<Menu> findParentMenus(List<Menu> list){
        List<Menu> parentList = new ArrayList<Menu>();

        Set<Object> parentIds = CollectionTools.convertListFeild2Set(list,"parentId");
        List<Menu> tempList  = null;
        if(!CollectionUtils.isEmpty(parentIds)){
            tempList = menuMapper.findByIdInOrderByMenuOrderAsc(parentIds);
        }
        if(tempList!=null && tempList.size()>0){
            parentList.addAll(tempList);
            findParentMenus(tempList);
        }
        return parentList;
    }
}
